﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Web.PayChannal.Code;
using System.Net;
using System.Collections;
using System.Text;
using ZLCMS.Business.Util;
using System.IO;
using System.Xml;
using ZLCMS.Business.WeixinService;
using DotNet.Common.NHibernateUtil;
using NHibernate;
using System.Text.RegularExpressions;
using ZLCMS.Data.Model;
using ZLCMS.Commands.Member.Commands.Member;
using DotNet.Common.Command;
using Senparc.Weixin.MP.AdvancedAPIs;
using NHibernate.Criterion;
using ZLCMS.Commands.Member.Commands.Order;
using ZLCMS.Commands.Sys.Commands.Order;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ZLCMS.Web.PayChannal.Weixinpay
{
    public partial class PaymentRequireNative : PaymentRequireBase
    {
        /// <summary>
        /// 二维码地址
        /// </summary>
        protected string QRCodeUrl { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (PaymentInfo.InterfaceId != "WXPAY")
            {
                ReportError("支付方式异常！");
                return;
            }



            string payNo = PaymentNo;
            //重新创建支付订单记录，微信不能对同一个交易号进行2次调用
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                IList<string> accList = session.CreateSQLQuery("select member_account from shop_order_info where payment_no=:pno group by member_account")
                    .SetParameter("pno", PaymentNo)
                    .List<string>();

                if (accList.Count != 1)
                {
                    ReportError("会员订单信息异常！");
                    return;
                }

                string acc = accList[0];

                //检查微信订单接口，判断是否支付成功
                SynchroPayStatusCommand synchroCmd = new WXPaySynchroPayStatusCommand();
                ICommandResult<SynchroPayStatusResult> synchroResult = synchroCmd.Execute(new SynchroPayStatusParameter() { PaymentNo = PaymentNo });
                //同步成功，表明商户订单已支付
                if (!synchroResult.Error)
                {
                    Response.Redirect("/Wap/Shop/OrderList.aspx");
                }

                //获取支付订单
                IList<string> orderList = session.CreateSQLQuery("select order_no from shop_order_info where payment_no=:pno group by member_account")
                    .SetParameter("pno", PaymentNo)
                    .List<string>();
                if (PaymentNo.IndexOf("_NATIVE") == -1)
                {
                    //未支付，生成新的支付号
                    payNo = PaymentNo + "_NATIVE";

                    //插入支付信息记录表
                    foreach (string orderNo in orderList)
                    {
                        session.Save(new ShopOrderPayment()
                        {
                            OrderNo = orderNo,
                            PaymentNo = payNo,
                            PayStatus = "0",
                            CreateDate = DateTime.Now,
                            PaymentId = PaymentInfo.Id
                        });

                        session.CreateQuery("update ShopOrderInfo set PaymentNo=:pno where OrderNo=:no")
                            .SetParameter("pno", payNo)
                            .SetParameter("no", orderNo)
                            .ExecuteUpdate();
                    }
                }
                session.Flush();

            }

            //使用新的payno
            PaymentNo = payNo;

            Hashtable paramHash = new Hashtable();
            paramHash["appid"] = PaymentInfo.AppId;
            paramHash["mch_id"] = PaymentInfo.UserId;
            paramHash["trade_type"] = "NATIVE";
            paramHash["nonce_str"] = GetNoncestr();
            paramHash["out_trade_no"] = payNo;
            paramHash["total_fee"] = ((int)(PaymentPrice * 100)).ToString();
            paramHash["notify_url"] = ServerUtil.GetRootURI() + "/PayChannal/Weixinpay/PaymentCallback.aspx";
            paramHash["body"] = ProductDesc;
            paramHash["spbill_create_ip"] = Request.UserHostAddress;
            paramHash["time_start"] = string.Format("{0:yyyyMMddHHmmss}", OrderTime);
            paramHash["time_expire"] = string.Format("{0:yyyyMMddHHmmss}", ExpireTime);

            //签名
            WXPayUtil.SetMD5Sign(paramHash, PaymentInfo.PrivateKey);



            Hashtable responseHash = WXPayUtil.GetResponseHash("wxordernative_" + PaymentNo, "https://api.mch.weixin.qq.com/pay/unifiedorder", paramHash);
            


            //获取支付链接
            string codeUrl = "";
            if (responseHash["return_code"] as string == "SUCCESS" && responseHash["result_code"] as string == "SUCCESS")
            {
                codeUrl = responseHash["code_url"] as string;
            }
            //调用接口出错     
            else
            {
                Response.Write(responseHash["return_msg"] + "=>" + responseHash["err_code_des"]);
                Response.End();
                return;
            }
            //调用接口失败，未知错误
            if (string.IsNullOrEmpty(codeUrl))
            {
                Response.Write("服务器忙");
                Response.End();
                return;
            }



            //使用资源服务器生成二维码
            string serverUrl = ParamKit.GetValue("SystemConfig", "IMAGESERVER_URL", "");
            string appid = ParamKit.GetValue("SystemConfig", "IMAGESERVER_APPID", "");
            string appsecrect = ParamKit.GetValue("SystemConfig", "IMAGESERVER_APPSECRECT", "");


            System.Security.Cryptography.HashAlgorithm md5 = System.Security.Cryptography.MD5.Create();

            string cfgStr = JsonConvert.SerializeObject(new { width = 500, height = 500, key = payNo, data = codeUrl });

            //计算签名
            string encypStr = appid + "#" + cfgStr + "#" + appsecrect;

            string sign = System.BitConverter.ToString(md5.ComputeHash(Encoding.GetEncoding("UTF-8").GetBytes(encypStr)))
                    .Replace("-", "").ToUpper();


            string postURL = serverUrl + "/GetBarcodeImg.aspx?appid=" + appid + "&cfg=" + HttpUtility.UrlEncode(cfgStr) + "&sign=" + sign;


            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(postURL);

            var httpWebResponse = (HttpWebResponse)wr.GetResponse();
            string responseContent;
            using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
            {
                responseContent = httpStreamReader.ReadToEnd();
            }
            JObject respObj = JsonConvert.DeserializeObject<JObject>(responseContent);

            //验证返回数据是否正确
            if (respObj["status"].Value<string>() == "1" && respObj["key"].Value<string>() == payNo && respObj["data"].Value<string>() == codeUrl)
            {
                QRCodeUrl = serverUrl + respObj["path"].Value<string>();
            }
            else
            {
                Response.Write("服务器忙");
                Response.End();
                return;
            }
            //把支付链接转成二维码
            //QRCodeUrl = QRCodeKit.RenderQrCode(codeUrl, 450, 450);

        }

    }
}